/**
 * 
 */
package edu.pku.sei.modeler.editparts;

import java.beans.PropertyChangeEvent;

import org.eclipse.draw2d.ConnectionLocator;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.draw2d.PolylineDecoration;
import org.eclipse.draw2d.PositionConstants;
import org.eclipse.draw2d.RotatableDecoration;

import edu.pku.sei.modeler.edit.parts.AbstractLinkEditPart;
import edu.pku.sei.modeler.model.structure.MetaShapeElement;
import edu.pku.sei.modeler.model.uml.BehaviorStateMachines.Transition;

/**
 * @author YanYan
 *
 */
public class TransitionEditpart extends UMLLinkEditpart {

	private RotatableDecoration targetDecor;
	
	private Label expressionLabel;
	
	public TransitionEditpart(MetaShapeElement conn) {
		super(conn);
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
	}
	private PolylineConnection getConnection() {
		return (PolylineConnection)getFigure();
	}
	
	
	protected IFigure createFigure() {
		PolylineConnection conn = new PolylineConnection();	
		conn.setLineStyle(1);
		
		expressionLabel = new Label(((Transition)this.getLink().getModelElement()).getCombinedExpression());
		
		ConnectionLocator expressionLocator = new ConnectionLocator(conn);
		expressionLocator.setRelativePosition(PositionConstants.NORTH);
		conn.add(expressionLabel,expressionLocator);
		
		return conn;
	}
	
	private PolylineDecoration createDecoration () {
		PolylineDecoration decoration = new PolylineDecoration();
		decoration.setScale(10, 5);
		return decoration;
	}
	
	
	protected void handlePropertyChanged(PropertyChangeEvent event) {
		refreshVisuals();
	}
	protected void refreshVisuals() {
		super.refreshVisuals();
		updateTargetDecoration();
		
		PolylineConnection conn = (PolylineConnection)this.getFigure();	
		conn.setLineStyle(1);
		conn.removeAllPoints();
		
		((Transition)this.getLink().getModelElement()).refreshExpression();
		expressionLabel.setText(((Transition)this.getLink().getModelElement()).getCombinedExpression());
		
		ConnectionLocator expressionLocator = new ConnectionLocator(conn);
		expressionLocator.setRelativePosition(PositionConstants.NORTH);
		conn.add(expressionLabel,expressionLocator);
		
	}
	
	private void updateTargetDecoration() {
		if (targetDecor == null) {
			targetDecor = createDecoration();
			getConnection().setTargetDecoration(targetDecor);
		}
	}
}
